<?php
// +----------------------------------------------------------------------
// | SL 2018.8.17
// +----------------------------------------------------------------------
// | Copyright (c) 2018~2018 http://sl.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: zq <1040657944@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model;


use think\Model;
use think\Db;

class CenterModel extends Model
{
    // 确定链接表名
    protected $name = 'center';
    //开启时间戳写入
    protected $autoWriteTimestamp = true;

    /**
     * 插入新的会员
    */
    public function insertCenter($param)
    {
        $param['password'] = md5($param['password'] . config('salt'));
        $param['thumb'] = '/static/admin/images/face.jpg'; // 默认头像
        try{
            $result =  $this->validate('CenterValidate')->allowField(true)->save($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                $login_info = Db::table("z_center")->where(['username' =>$param['username'],'password' => $param['password']])->find();
                session('center_info',$login_info);
                return msg(1, url('forum/index'), '注册成功!');
            }
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }

    }

    /**
     * 更新会员信息
     */
    public function updateCenter($param)
    {
        if($this->allowField(true)->isUpdate(true)->save($param)){
           return $this->refreshSession($param['id']);
        }
    }

    /**
     * 获取单条数据信息
     */
    public function getOneCenter($where)
    {
        return $this->where($where)->find();
    }

    /**
     * 获取单条数据信息
     */
    private function refreshSession($cid)
    {
        $center_info = $this->find($cid);
        if( $center_info ){
            $center_info = $center_info->toArray();
            session('center_info',$center_info);
            return true;
        }
        return false;
    }

    /**
     * 登陆次数加1
     */
    public function incLoginNum($where)
    {
        return $this->where($where)->setInc('login_num');
    }

    /**
     * 签到活跃榜(最新签到)
     */
    public function signinNew(){
        return $this->where(true)->order('last_sign_time desc')->select();
    }

    /**
     * 签到活跃榜(今日最快)
     */
    public function signinFast(){
        return $this->where(true)->order('last_sign_time asc')->limit(1)->select();
    }


    /**
     * 签到活跃榜(总签到榜)
     */
    public function signinTop(){
        return $this->where(true)->order('all_sign_num desc')->select();
    }



}